<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>刮刮卡</title>
    <style>
        html, body{
            width: 100%;
            height: 100%;
            padding: 0;
            margin: 0;
        }
        #container{
            position: absolute;
            width: 320px;
            height: 150px;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
            border: 1px solid gray;
        }
        #inner{
            display: table;
            text-align: center;
            width: 100%;
            height: 100%;
            font-size: 60px;            
        }
        #inner p{
            display: table-cell;
            vertical-align: middle;
            padding: 0;
            margin: 0;
        }
        #mask{
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="inner"><p>HaHa</p></div>
        <canvas id="mask"></canvas>
    </div>
</body>
<script>
    let canvas = document.querySelector("#mask");
    let w = canvas.width;
    let h = canvas.height;
    let [offsetX, offsetY] = getDOMOffset(canvas);

    console.log(offsetX, offsetY);

    let canClear = false;;

    let ctx = canvas.getContext("2d");


    ctx.fillStyle="#888888";
    ctx.fillRect(0, 0, w, h/2);

    ctx.globalCompositeOperation = 'destination-out';


    window.addEventListener("mousedown", ()=>{canClear = true});
    window.addEventListener("mouseup", ()=>{canClear = false});
    window.addEventListener("mousemove", clear);

    function clearCircle(x, y, r){
        ctx.beginPath();
        ctx.arc(x, y, r, 0, 2*Math.PI);
        ctx.fillStyle="red";
        ctx.fill();
    }

    function clear(event){
        if(!canClear)return;
        let x = event.clientX - offsetX;
        let y = event.clientY - offsetY;
        clearCircle(x, y, 20);
    }

    /**
    offsetLeft 得到该元素的左边界到父元素的左边界的距离
    event.clientX 得到鼠标相对于视口原点的距离
    */
    function getDOMOffset(dom){
        let tmpX = dom.offsetLeft;
        let tmpY = dom.offsetTop;

        let parent = dom.parentNode;

        while(parent && parent!==document){
            tmpX += parent.offsetLeft;
            tmpY += parent.offsetTop;
            parent = parent.parentNode;
        }

        return [tmpX, tmpY];
    }

</script>
</html>